#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>


int main()
{
    // 1.创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);   // 管道创建

    if(n == -1)
    {
        perror("pipe");
        exit(1);
    }

    // 2.创建子进程
    pid_t id = fork();   

    // 让子进程写数据， 父进程读数据
    if(id == 0)
    {
        // 子进程发送数据
        // 3. 关闭不需要的fd
        close(pipefd[0]);

        // 4. 写数据
        // char send_buffer[1024] = {0};
        std::string message = "[Child process]# Send message to you";

        while(true)
        {
            // 子进程间隔一秒发送数据
            ssize_t sz = write(pipefd[1], message.c_str(), message.size());
            if(sz > 0) sleep(1);
            else break;
        }

        close(pipefd[1]);
        exit(1);
    }

    // 父进程读取数据
    // 3. 关闭不需要的fd
    close(pipefd[1]);

    // 4. 开始读取数据
    char read_buffer[1024] = {0};
    int count = 0;

    while(true)
    {
        ssize_t sz = read(pipefd[0], read_buffer, 1024);
        if(sz > 0)
        {
            read_buffer[sz] = '\0';
            std::cout << "[" << getpid() << "]" << read_buffer << ", count:" << ++count << std::endl;

            if(count == 5)
            {
                // 关掉读端
                // 终止读取死循环
                close(pipefd[0]);
                break;
            }
        }
        else break;
    }

    // 5. 父进程阻塞等待子进程退出
    int status = 0;
    waitpid(id, &status, 0);

    std::cout << "child process exit, write end, exit code:" \
    << (status & 0x7F) << ", core_dump:" << ((status >> 7) & 1) << std::endl;

    return 0;
}